package com.dgz.coolshark.controller;

import com.dgz.coolshark.mapper.UserMapper;
import com.dgz.coolshark.pojo.dto.UserLoginDto;
import com.dgz.coolshark.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


/**
 * @Author duguozheng
 * @Date 2023/04/27  14:53
 * @Description UserController
 * @Version 1.0
 */
@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;
    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDto userLoginDto, HttpServletResponse response, HttpSession session) {
        UserVo userVo = userMapper.selectByUsername(userLoginDto.getUsername());
        if (userVo != null) {
            if (userVo.getPassword().equals(userLoginDto.getPassword())) {
                //判断是否需要记住用户名和密码
                if (userLoginDto.isRem()){
                    Cookie c1 = new Cookie("username", userLoginDto.getUsername());
                    Cookie c2 = new Cookie("password", userLoginDto.getPassword());
                    c1.setMaxAge(60*60*24*30);
                    response.addCookie(c1);
                    response.addCookie(c2);
                }
                /*把当前登录成功的userVo保存到session里面*/
                session.setAttribute("user", userVo);
                return 1;
            }
            return 2;
        }
        return 3;
    }
    @RequestMapping("/currentUser")
    public UserVo currentUser(HttpSession session) {
        return (UserVo) session.getAttribute("user");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session) {
       session.removeAttribute("user");
    }

}
